package com.zhongkeruan.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author yangyao
 * @Description: JwtUtil
 * @date 2019/1/12 16:00
 */
@ConfigurationProperties(prefix = "jwt.config")
public class JwtUtil {

    private String key;

    private Long ttl;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public Long getTtl() {
        return ttl;
    }

    public void setTtl(Long ttl) {
        this.ttl = ttl;
    }

    /**
     * 生成token
     *
     * @param userId
     * @param userName
     * @param role
     * @return
     */
    public String createToken(String userId, String userName, String role) {
        Long nowTime = System.currentTimeMillis();
        Date now = new Date();
        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(userId)
                .setIssuedAt(new Date())
                .setSubject(userName)
                .claim("role", role)
                .signWith(SignatureAlgorithm.HS256, key);
        if (ttl > 0) {
            jwtBuilder.setExpiration(new Date(nowTime + ttl));
        }
        return jwtBuilder.compact();
    }

    /**
     * 解析token
     * @param token
     * @return
     */
    public Claims parseToken(String token) {
        return Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(token)
                .getBody();
    }
}
